import { reactive, watch } from 'vue'
import { getItemState } from '../state-item'

/**
 * 设置监听，实现外部属性和内部属性的同步
 * @param props 组件的 props
 * @returns 
 */
export default function myWatch() {
  
  const state = getItemState()

  const model = reactive({
    controlType: 101
  })
  const partModel = reactive({})
  
 

  watch(() => state.base1.controlType, (type) => {
    setTimeout(() => {
      model.controlType = type
    }, 600)

  }, {immediate: true})

   // 内部 同步 给 props
  watch(partModel, () => {
    state.extend.$patch( partModel )
    // , {immediate: true}
  })
  
  // 同步给 左面的控件类型
  watch(() => model.controlType, () => {
    // 同步 控件类型
    state.base1.controlType = model.controlType
  })
  
  // 控件类型变更后，清空扩展属性
  watch(() => model.controlType, () => {
    // 清空 扩展属性
    const keys = Object.keys(state.extend)
    keys.forEach(key => {
      delete state.extend[key]
    })
  }, {immediate: true})

  const setup = (_model) => {

    // 外部设置属性的时候，同步
    watch(() => state.isRolad, () => {
      // 设置类型
      _model.controlType = state.base1.controlType
      const keys = Object.keys(state.sourceExtend)
      keys.forEach(key => {
        _model[key] =  state.sourceExtend[key]
      })
    })
  }
  
  return {
    setup,
    model,
    partModel,
  }
}